﻿using Microsoft.Phone.Shell;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using TheVerge.Base.Platform;

namespace TheVerge.Phone.Imp
{
    public class PhonePinner : IPinner
    {
        public void Pin(IPinnable pinnable)
        {
            //-- Get the current page we're on
            var pageUri = ((App)Application.Current).RootFrame.CurrentSource.ToString();
            var xamlIndex = pageUri.IndexOf(@"xaml") + 4;

            //-- Build the uri with the Query Strings
            var sb = new StringBuilder(pageUri.Substring(0, xamlIndex));
            sb.Append(@"?");
            foreach (var qs in pinnable.QueryStrings.Keys)
            {
                sb.AppendFormat(@"{0}={1}&", qs, pinnable.QueryStrings[qs]);
            }

            var uri = new Uri(sb.ToString(), UriKind.Relative);

            CreateOrUpdateTile(pinnable.DisplayName, pinnable.Tile, uri);
        }

        private static void CreateOrUpdateTile(string title, Uri tile, Uri uri) 
        {
            var tiledata = new StandardTileData { Title = title };
            
            if (tile.IsAbsoluteUri)
            {
                PhoneImageSaver.Save(tile, tileUri =>
                {
                    tiledata.BackgroundImage = tileUri;

                    CreateOrUpdateTile(tiledata, uri);
                }, error => {
                    MessageBox.Show("There was an error pinning the tile.");
                });

                return;
            }

            tiledata.BackgroundImage = tile;

            CreateOrUpdateTile(tiledata, uri);
		}

        private static void CreateOrUpdateTile(StandardTileData data, Uri uri)
        {
            //-- Add default application background image
            data.BackBackgroundImage = new Uri(@"/Images/Tile.png", UriKind.Relative);

            //-- If we already have a Shell Tile for this pageUri, we can just
            // update the tile.
            foreach (var st in ShellTile.ActiveTiles)
            {
                if (st.NavigationUri == uri)
                {
                    st.Update(data);

                    //-- Notify the user the tile was created.
                    MessageBox.Show(string.Format("Successfully updated {0} tile.", data.Title));
                    return;
                }
            }

            //-- If this is a new Shell Tile, then lets go create one!
            ShellTile.Create(uri, data);
        }
    }
}
